const mqtt = require('mqtt')
const sd = require('silly-datetime');
var mqttClient = mqtt.connect(config.mqttOptions)
let api = require(__basename + '/api/api.js');

var schedule = require('node-schedule');

function cutDate(str){
    let arr = str.split('a')
   /* 
    0电压[ 0.0001V] 
    1电流 [0.0001A] 
    2电功率[0.0001W] 
    3电能量 [0.0001kwh] 
    4电功因[0.001]
    */
    return arr;

}
var ruleTime     = new schedule.RecurrenceRule();
ruleTime.hour  = [0]; //每日凌晨执行一次 范围0-23
ruleTime.minute  = 0; //范围0-59
schedule.scheduleJob(ruleTime, function(){
  mqttClient.publish('LJHCON1', '1') // 发送指令，当硬件层接订阅收到后执行计量模块清零
});

class MymqttCl {
    init() {
        console.log('11')
        mqttClient.on('connect', function () {
            // 订阅主题
            mqttClient.subscribe('run', function (err) {
                if (!err) {
                    mqttClient.publish('run', 'success open the server in mqtt')
                }
            })
            mqttClient.subscribe('LJH', function (err) {
                if (!err) {
                    mqttClient.publish('run', 'success open the server => LJH')
                }
            })
            mqttClient.subscribe('LJH1', function (err) {
                if (!err) {
                    mqttClient.publish('run', 'success open the server => LJH1')
                }
            })
            mqttClient.subscribe('LJH2', function (err) {
                if (!err) {
                    mqttClient.publish('run', 'success open the server => LJH2')
                }
            })
            mqttClient.subscribe('LJHCON1', function (err) {
                if (!err) {
                    //电能清空功能
                    mqttClient.publish('run', 'success open the server => LJHCON1')
                }
            })
        })

        mqttClient.on('message', function (topic, message) {
            // message is Buffer
            let nowtime=sd.format(new Date(), 'YYYY-MM-DD HH:mm');

            console.log(nowtime,'topic=>', topic);
            console.log(message.toString())
            // if(topic == "run"){
            //     console.log(message.toString())
            // }
            // mqttClient.end()
            if(topic == 'LJH2' || topic == 'LJH1'){
               let arr = cutDate(message.toString());
                    console.log('arr=>',arr)
                    let subObj = {}
                    if(arr[0]==""){
                        subObj = {
                           vData:arr[1],
                           aData:arr[2],
                           pData:arr[3],
                           total:arr[4],
                        }
                    }else{
                        subObj = {
                           vData:arr[0],
                           aData:arr[1],
                           pData:arr[2],
                           total:arr[3],
                        }
                    }

                
                    let where = {
                        where: {
                            topic:topic
                        }
                    }
                    api.update('Latest', subObj, where).then(subres => {
                        console.log(subres);
                    });

                    let month = new Date().getMonth() + 1;
                    let nowDate = new Date().getDate();
                    // 查找订阅号对应的id
                    let whereobj = {
                        where:{
                            topic:topic
                        }
                    }
                    api.findAll('Latest',whereobj).then(result=>{
                        // 先获取userID

                        let whereobj2 = {
                            where:{
                                userId:result[0].userId,
                                month:month
                            }
                        }

                        // 查找是存在该月份数据 不存在则创建，存在则更新
                        api.findAll('Order',whereobj2).then(resultOrder=>{
                            if(resultOrder.length < 1){

                                let createObj = {
                                    userId:result[0].userId,
                                    month:month,
                                } 
                                createObj[`date_${nowDate}`] = arr[4];
                                api.createData('Order',createObj)
                            }else{
                                let updateObj = {};
                                updateObj[`date_${nowDate}`] = arr[4];
                                api.update('Order', updateObj, whereobj2)
                            }


                        })


                    })

            }

        })

    }
}
module.exports = new MymqttCl()